﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace StableDiffusionTools.Extensions
{
    public static class JsonExtensions
    {
        private static readonly JsonWriterOptions indentedOptions = new JsonWriterOptions()
        {
            Indented = true,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };

        private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
        {
            WriteIndented = true,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };

        public static string ToStringIndented(this JsonElement value)
        {
            string indented = "";
            if (value.ValueKind != JsonValueKind.Undefined)
            {
                try
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        using (Utf8JsonWriter writer = new Utf8JsonWriter(stream, indentedOptions))
                        {
                            value.WriteTo(writer);
                            writer.Flush();
                            indented = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
                        }
                    }
                }
                catch (Exception) { }
            }

            return indented;
        }

        public static string ToStringIndented(this JsonObject value)
        {
            return value.ToJsonString(jsonSerializerOptions);
        }
    }
}
